package com.marianhello.bgloc;

import android.util.Log;
import android.net.Uri;

//import java.util.List;
import java.util.Map;
import java.util.Iterator;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import org.json.JSONObject;

public class HttpPostService {

    private static final String TAG = "HttpPostService";
    private static final int REQUEST_TIME_OUT = 5000;

    public static int postJSON(String url, Object json, Map headers)	{
        try {
        	url = "http://192.168.31.155:3000/locations";

            String jsonString = json.toString();
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            // conn.setConnectTimeout(5000);
            // conn.setDoInput(true);

            conn.setDoOutput(true);
            //conn.setFixedLengthStreamingMode(jsonString.length());
            // conn.setChunkedStreamingMode(0);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            conn.setRequestProperty("Accept-Language", "zh-CN,en-US;q=0.8");
            conn.setRequestProperty("Origin", "file://");
             conn.setRequestProperty("Content-Type", "application/json");
//            Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
//            while (it.hasNext()) {
//                Map.Entry<String, String> pair = it.next();
//                conn.setRequestProperty(pair.getKey(), pair.getValue());
//            }

            OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream());
            os.write(json.toString());
            os.flush();
            os.close();

            return conn.getResponseCode();

        } catch (Throwable e) {
            Log.w(TAG, "Exception posting json: " + e);
            e.printStackTrace();
            return 0;
        }
    }

    public static String postGpsData(String url, JSONObject gpsData, Map headers, String compressMethod) throws IOException {
    	url += "/trip/upload";
//    	url = "http://192.168.0.125:1337/trip";
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
//        Log.w(TAG, "Request header:");
        while (it.hasNext()) {
            Map.Entry<String, String> pair = it.next();
            conn.setRequestProperty(pair.getKey(), pair.getValue());
        }

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setConnectTimeout(REQUEST_TIME_OUT);
        conn.setReadTimeout(REQUEST_TIME_OUT);
        conn.setRequestMethod("POST");

//        conn.setFixedLengthStreamingMode(jsonString.length());

//        Uri.Builder builder = new Uri.Builder();
//        builder.appendQueryParameter("fun", "transfer").appendQueryParameter("data", gpsData.toString()).appendQueryParameter("package", packageNum.toString()).appendQueryParameter("method", compressMethod);

        OutputStreamWriter os = null;
        try {
            os = new OutputStreamWriter(conn.getOutputStream());
            os.write(gpsData.toString());

        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
        int status = conn.getResponseCode();
        if (status != 200) {
            Log.w(TAG, "Post GPS respons is failed with code " + status);
            LogUtil.d(TAG, "Post GPS respons is failed with code " + status);
            LogUtil.d(TAG, "Post GPS respons exception message is " + conn.getResponseMessage());
        	return null;
        }

//        Log.w(TAG, "Response header:");
//        Map<String, List<String>> map = conn.getHeaderFields();
//
//    	for (Map.Entry<String, List<String>> entry : map.entrySet()) {
//    		Log.w(TAG, "Key : " + entry.getKey() + " ,Value : " + entry.getValue());
//    	}

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();

        String res = sb.toString();
//        Log.w(TAG, "Original is : " + res);

        return res;
    }

    public static String postStartTrip(String url, JSONObject startBundle, Map headers) throws IOException {
        Log.i(TAG,"startBundle ->" + startBundle);
        LogUtil.d(TAG,"startBundle ->" + startBundle);
    	  url += "/trip/start";
        Log.i(TAG,"url ->" + url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pair = it.next();
            conn.setRequestProperty(pair.getKey(), pair.getValue());
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
//        conn.setFixedLengthStreamingMode(jsonString.length());
        conn.setConnectTimeout(REQUEST_TIME_OUT);
        conn.setReadTimeout(REQUEST_TIME_OUT);
        conn.setRequestMethod("POST");

//        Uri.Builder builder = new Uri.Builder();
//        builder.appendQueryParameter("CarId", startBundle.optString("CarId")).appendQueryParameter("Mass", startBundle.optString("Mass"));

        OutputStreamWriter os = null;
        try {
            os = new OutputStreamWriter(conn.getOutputStream());
//            Log.d(TAG, "builder: " + builder.build().toString().substring(1));
            os.write(startBundle.toString());

        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
        int status = conn.getResponseCode();
        LogUtil.d(TAG, "Post start trip respons is with code " + status);
        if (status != 200) {
        	Log.w(TAG, "Post start trip respons is failed with code " + status);
          LogUtil.d(TAG, "Post start trip respons is failed with code " + status);
        	return null;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();

        String res = sb.toString();
        Log.w(TAG, "Post start trip respons is " + res);
        return res;
    }

    public static String postStopTrip(String url, JSONObject stopBundle, Map headers) throws IOException {
    	url += "/trip/stop";
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        Iterator<Map.Entry<String, String>> it = headers.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pair = it.next();
            conn.setRequestProperty(pair.getKey(), pair.getValue());
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
//        conn.setFixedLengthStreamingMode(jsonString.length());
        conn.setConnectTimeout(REQUEST_TIME_OUT);
        conn.setReadTimeout(REQUEST_TIME_OUT);
        conn.setRequestMethod("POST");


//        Uri.Builder builder = new Uri.Builder();
//        builder.appendQueryParameter("fun", "stop").appendQueryParameter("data", locationArray.toString()).appendQueryParameter("package", packageNum.toString()).appendQueryParameter("method", "json");

        OutputStreamWriter os = null;
        try {
            os = new OutputStreamWriter(conn.getOutputStream());
            os.write(stopBundle.toString());

        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
        int status = conn.getResponseCode();
        if (status != 200) {
        	Log.w(TAG, "Post stop trip respons is failed with code" + status);
        	return null;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();

        String res = sb.toString();
        Log.w(TAG, "Post stop trip respons is " + res);
        return res;
    }

    public static String postRemoteLog(String url, Object json, Map headers)	throws IOException {
    	url += "/classes/Log";
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

        conn.setRequestProperty("X-Parse-Application-Id", "lcmm_app_id");
        conn.setRequestProperty("Content-type", "application/json");
        conn.setDoOutput(true);
        conn.setDoInput(true);
//        conn.setFixedLengthStreamingMode(jsonString.length());
        conn.setConnectTimeout(3000);
        conn.setReadTimeout(3000);
        conn.setRequestMethod("POST");

//        Uri.Builder builder = new Uri.Builder();
//        builder.appendQueryParameter("fun", "stop").appendQueryParameter("data", locationArray.toString()).appendQueryParameter("package", packageNum.toString()).appendQueryParameter("method", "json");

        OutputStreamWriter os = null;
        try {
            os = new OutputStreamWriter(conn.getOutputStream());
            os.write(json.toString());

        } finally {
            if (os != null) {
                os.flush();
                os.close();
            }
        }
        int status = conn.getResponseCode();
        if (status < 200 || status >= 300) {
        	Log.w(TAG, "Post remote log respons is failed with code" + status);
        	return null;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();

        String res = sb.toString();
    	return res;
    }

}
